const ci = require('miniprogram-ci')
const { green, bold, red } = require('kolorist');
let { version } = require('./package.json')
const { prompt, AutoComplete  } = require('enquirer');

version = 'V' + version

if (!version) version = 'v1.0.0'

const project = new ci.Project({
  appid: 'wx7a1eab2b0f9bfa59',
  type: 'miniProgram',
  projectPath: process.cwd() + '/dist/dev/mp-weixin',
  privateKeyPath: process.cwd() + '/key/private.wx7a1eab2b0f9bfa59.key',
  ignores: ['node_modules/**/*','key/**/*'],
})

// 终端显示信息
const step = (msg) => console.log(bold(green(`[step] ${msg}`)));
const stepErr = (msg) => console.log(bold(red(`[error] ${msg}`)));

// 发布模式   上传 or 预览
const relaseMode = new AutoComplete({
  name: 'flavor',
  message: '请选择发布方式',
  choices: [
    '预览',
    '上传'
  ]
});

submit()


async function submit(){
  try {
    const release = await relaseMode.run()
    const desc = await getVersionDesc()

    if(release === '上传'){
      upload(desc)
    }else{
      preview(desc)
    }
    
  } catch (error) {
    stepErr(error)
  }
}
// 上传模式
async function upload(desc){
  try {
    const result = await ci.upload({
      robot: 3,
      project,
      version,
      desc,
      setting: {
          minify: true,
      },
    })
    step('上传成功')
    step(JSON.stringify(result) )
  } catch (error) {
    stepErr(JSON.stringify(error)) 
  }

}
// 预览模式
async function preview(desc){
  try {
    const result = await ci.preview({
      project,
      desc, // 此备注将显示在“小程序助手”开发版列表中
      setting: {
        es6: true,
      },
      qrcodeFormat: 'image',
      qrcodeOutputDest: process.cwd() + '/key/preview.jpg',
      onProgressUpdate: console.log,
      pagePath: 'pages/index/index', // 预览页面
      // searchQuery: 'a=1&b=2',  // 预览参数 [注意!]这里的`&`字符在命令行中应写成转义字符`\&`
    })
    step('预览成功')
    step(JSON.stringify(result) )
  } catch (error) {
    stepErr(JSON.stringify(error)) 
  }
}

// 获取版本描述
async function getVersionDesc(){
  const { desc } = await prompt({
                    type: 'input',
                    name: 'desc',
                    message: `请输入${version}版本描述`,
                    // default:new Date() + '上传'
                  })
  if(!desc) desc = new Date() + '上传'    
  step(desc)           
  return desc
}

